package com.wangliang.deepseek.listeners;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.wangliang.deepseek.service.DeepSeekService;
import org.jetbrains.annotations.NotNull;

/**
 * 项目生命周期监听器
 * 负责处理项目打开和关闭时的初始化和清理工作
 */
public class DeepSeekProjectListener implements StartupActivity.DumbAware {
    private static final Logger LOG = Logger.getInstance(DeepSeekProjectListener.class);
    private DeepSeekService deepSeekService;

    @Override
    public void runActivity(@NotNull Project project) {
        LOG.info("Project starting: " + project.getName());
        try {
            // 初始化服务
            deepSeekService = new DeepSeekService();

            // 确保工具窗口正确初始化
            ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
            ToolWindow toolWindow = toolWindowManager.getToolWindow("DeepSeek Assistant");
            if (toolWindow != null) {
                toolWindow.activate(null);
            }

            // 添加项目关闭监听器
            project.getMessageBus().connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
                @Override
                public void projectClosing(@NotNull Project closingProject) {
                    if (project.equals(closingProject)) {
                        cleanup(project);
                    }
                }
            });

            // 其他初始化工作...
            LOG.info("DeepSeek Assistant initialized for project: " + project.getName());
        } catch (Exception e) {
            LOG.error("Failed to initialize DeepSeek Assistant", e);
        }
    }

    /**
     * 检查插件是否已经为指定项目初始化
     */
    public boolean isInitialized(@NotNull Project project) {
        return deepSeekService != null &&
                ToolWindowManager.getInstance(project)
                        .getToolWindow("DeepSeek Assistant") != null;
    }

    /**
     * 手动初始化插件（如果需要的话）
     */
    public void initializeIfNeeded(@NotNull Project project) {
        if (!isInitialized(project)) {
            runActivity(project);
        }
    }

    /**
     * 手动清理插件资源
     */
    private void cleanup(@NotNull Project project) {
        LOG.info("Cleaning up project: " + project.getName());
        try {
            // 清理服务资源
            if (deepSeekService != null) {
                deepSeekService.shutdown();
                deepSeekService = null;
            }

            // 关闭工具窗口
            ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
            ToolWindow toolWindow = toolWindowManager.getToolWindow("DeepSeek Assistant");
            if (toolWindow != null) {
                toolWindow.hide(null);
            }

            // 其他清理工作...
            LOG.info("DeepSeek Assistant cleaned up for project: " + project.getName());
        } catch (Exception e) {
            LOG.error("Failed to cleanup DeepSeek Assistant", e);
        }
    }
}